// 财小白微信小程序
// app.js

// 引入加异步假接口 迟D删
require('./utils/wxFakeReq')

// 引用工具方法封装文件
require('./utils/util')
// 引用微信api封装文件
require('./utils/wxApiPkg')
// 引入微信公共方法封装文件
let { wxPubPkg, } = require('./utils/wxPublicPkg')
// 引入接口封装
require('./utils/request')
// 引入权限接口封装
require('./utils/permission')
// 引入路径文件
require('./utils/parseUrl')

//引入获取定位授权转换中文地址的函数
require('./utils/location.js')
import { config } from "./utils/config";
import { setWxInfoStorage } from "./utils/init";
// 验证表单
wx.$validForm = (fieldList, validObj) => {
  return new Promise((resolve, reject) => {
    let valid = true
    if (fieldList && validObj && Array.isArray(fieldList) && typeof validObj === 'object') {
      let validArr = []

      fieldList.forEach(item => {
        let { is_null, type, field_id, fieldName, } = item
        field_id = field_id || fieldName
        if ((is_null === false && type !== 'autonumber')) {  // 必填
          // 验证结果不是true的
          if (!validObj[field_id]) validArr.push(false)
        }
      })
      valid = validArr.includes(false) ? false : true
    } else {
      valid = false
    }
    resolve(valid)
  })
};

//230120 yan + 获取小程序标题
wx.$getBarTitle = (id) => {
  wx.$post(1, 'Authorize/get_miniprogram_name', id ? { system_id: id } : {}).then(res => {
    if (res.errcode != 0) return;
    wx.setStorageSync('bar_title', res.data.row[0] && res.data.row[0].WXMiniProgram_name);
  })
}

App({
  globalData: {
    isSendWXgps: false,
    sendWXgpsVehicle_no: null,
    sendWorkerLocation: null
  },
  onLaunch () {
    // 小程序更新提示
    wxPubPkg.autoUpdate();

    //根据appId获取跳转页面和默认系统号
    setWxInfoStorage();

    let defSystemId = wx.getStorageSync('wxinfo-defSystemId');
    //方通小程序默认系统号
    wx.$getBarTitle(defSystemId);

  },
  wxLocation () {
    return new Promise((resolve, reject) => {
      wx.$getLocation(false).then(res => {
        this.mapGeocoder(res).then(result => {
          resolve(result);
        })
      }, reject)
    })
  },
  //腾讯地图api逆地址转换
  mapGeocoder (latlng) {
    let url = 'map/tencent/ws/geocoder/location';
    let { latitude, longitude } = latlng;
    return new Promise(resolve => {
      wx.$post(2, url, {
        "key": config.mapKey,
        "location": `${latitude},${longitude}`,
        "get_poi": "",
        "poi_options": "",
        "output": "",
        "callback": ""
      }, false, true).then(res => {
        resolve(res)
      })
    })
  },
  timeOutSendWXlocation (vehicle_no) {
    let that = this;
    that.wxLocation().then(res => {
      that.sendwxGps({ vehicle_no, ...res })
      wx.setStorageSync('siji_isSendWXgps', true);
      that.globalData.isSendWXgps = true;
      wx.$post(5, 'ZTAuth/CarOnline');// 上线接口
      wx.setStorageSync('siji_sendWXgpsVehicle_no', vehicle_no)
      that.globalData.sendWorkerLocation = setInterval(() => {
        that.wxLocation().then(locationArr => {
          that.sendwxGps({ vehicle_no, ...locationArr })
        })
      }, 15000)
    })
  },
  sendwxGps (data) {
    return new Promise(resolve => {
      const postData = [
        {
          "vehicle_no": data.vehicle_no,
          "longitude": data.result.location.lng,
          "latitude": data.result.location.lat,
          "speed": 0,
          "direction": 0,
          "data_time": wx.$util.formatTime(new Date()),
          "addr": data.result.address
        }
      ]
      wx.$post(5, 'GPS', postData, false, true).then(res => {
        resolve(res)
      })
    })
  },
  onShow () {
    this.RestartsendGPS();
  },
  RestartsendGPS () {
    // 判断重启GPS
    if (wx.getStorageSync('siji_isSendWXgps')) {
      if (!this.globalData.isSendWXgps && !this.globalData.sendWXgpsVehicle_no) {
        this.globalData.isSendWXgps = wx.getStorageSync('siji_isSendWXgps');
        this.globalData.sendWXgpsVehicle_no = wx.getStorageSync('siji_sendWXgpsVehicle_no');
      }
      if (this.globalData.sendWorkerLocation == null || !this.globalData.sendWorkerLocation) {
        this.timeOutSendWXlocation(this.globalData.sendWXgpsVehicle_no)
      }
    }
  },
  closeSendGPS () {
    this.globalData.isSendWXgps = false;
    this.globalData.sendWXgpsVehicle_no = null;
    clearInterval(this.globalData.sendWorkerLocation);
    this.globalData.sendWorkerLocation = null;
    wx.$post(5, 'ZTAuth/CarOffline');// 下线接口
    wx.setStorageSync('siji_isSendWXgps', this.globalData.isSendWXgps);
    wx.setStorageSync('siji_sendWXgpsVehicle_no', this.globalData.sendWXgpsVehicle_no)
  }
  // onLaunch() {
  //   // 展示本地存储能力
  //   const logs = wx.getStorageSync('logs') || []
  //   logs.unshift(Date.now())
  //   wx.setStorageSync('logs', logs)

  //   // 登录
  //   wx.login({
  //     success: res => {
  //       // 发送 res.code 到后台换取 openId, sessionKey, unionId
  //     }
  //   })
  // },
})
